<?php
session_start();
$username = $_SESSION['username'] ?? '';

function getNewFriendRequests($username) {
    $messagesFile = __DIR__ . '/messages/system_messages.json';
    if (!file_exists($messagesFile)) return 0;
    
    $messages = json_decode(file_get_contents($messagesFile), true) ?? [];
    $count = 0;
    
    foreach ($messages as $msg) {
        if ($msg['type'] === 'friend_request' && 
            $msg['to_user'] === $username && 
            ($msg['status'] ?? 'pending') === 'pending') {
            $count++;
        }
    }
    
    return $count;
}

header('Content-Type: application/json');
echo json_encode(['count' => getNewFriendRequests($username)]);
?>